//
//  OrdersViewController.m
//  SeaMelonSeeds_Counselor
//
//  Created by 尤振宇 on 2017/7/14.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "OrdersViewController.h"
#import "OrderHeaderView.h"
#import "OrderTableViewCell.h"
#import "Order.h"
#import "PersonalDetailsViewController.h"
#import "LoginViewController.h"
#import "OrderDetailsViewController.h"
#import "FaceToFaceTableViewCell.h"

#import "ClassificationViewController.h"
#import "ClassificationCell.h"
#import "GaugeApi.h"
#import "RefusedViewController.h"
#import "OrderListApi.h"
#import "OrderApi.h"

CGFloat layer_Y = 300;

@interface OrdersViewController () 
@property(nonatomic,strong)OrderHeaderView *header;
@property(nonatomic,weak)CALayer *redundantLayer;

@property(nonatomic,weak)MASViewConstraint *header_Y;

@property(nonatomic,weak)ClassificationViewController *classificationVC;

@property(nonatomic,strong)NSArray <WKApi *>*apis;
@property(nonatomic,strong)NSArray <NSMutableArray *>*datas;
@end

@implementation OrdersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    self.tableView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [@"eaeaea" colorWithHexString];
    
    self.headerViewH.constant = 0;
    self.fromTop.constant = 0;
    
    [self.tableView registerCellWithNib:@"OrderTableViewCell"];
    [self.tableView registerCellWithNib:@"FaceToFaceTableViewCell"];
    
    [self configNotDataView:[UIImage imageNamed:@"noOrder"] text:@"暂无订单"];
    
    [self.view addSubview:self.header];
    NSArray *arr = [self.header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(self.header.height);
        make.width.mas_equalTo(self.header.width);
    }];
    self.header_Y = arr[0];
    
    [self addMj_footer];
    
    MJRefreshNormalHeader *refresh = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    /*调整mj_header 的y*/
    refresh.ignoredScrollViewContentInsetTop = - self.header.height;
    refresh.stateLabel.textColor = [UIColor whiteColor];
    refresh.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
    [self.tableView setMj_header:refresh];

    
    CALayer *layer = [[CALayer alloc]init];
    layer.frame = CGRectMake(0, -layer_Y, SCREEN_WIDTH, self.header.height + 60 + layer_Y);
    layer.backgroundColor = k65ACFE.CGColor;
    [self.view.layer insertSublayer:layer atIndex:0];
    self.redundantLayer = layer;
    
    [self loadAllListData];

    
    [[NSNotificationCenter defaultCenter]addObserverForName:kLoginNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       
        [self loadAllListData];
    }];
    
    if (![Config isLogin]) {
        [self presentViewController:[[LoginViewController alloc]init] animated:NO completion:nil];
    }
    // Do any additional setup after loading the view.
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

-(void)loadAllListData
{
    [self.datas makeObjectsPerformSelector:@selector(removeAllObjects)];
    
    WeakSelf(self)
    for (int i = 0; i<self.apis.count; i++) {
        WKApi *api = weakself.apis[i];
        
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            if (kCode(request.responseJSONObject)) {
                NSMutableArray *dataArray = weakself.datas[i];
                if (api.page == 1) {
                    [dataArray removeAllObjects];
                }
                NSArray *arr = [[request.responseJSONObject objectForKey:@"data"] objectForKey:@"list"];
                for (NSDictionary *dic in arr) {
                    Order *order = [Order new];
                    [order setValuesForKeysWithDictionary:dic];
                    [dataArray addObject:order];
                }
                
//                Order *order = [[Order alloc]init];
//                order.user_avatar = @"http://n.sinaimg.cn/sinacn/20170817/5cf1-fykcpru7542138.jpg";
//                order.count = 5;
//                order.total_fee = 1000;
//                order.surplus_count = 2;
//                order.nickname = @"5678";
//                order.age = 23;
//                order.sex = 1;
//                order.problemDescription = @"汽车的logo，可以说直接代表了一个品牌的精髓，其重要性自然不言而喻。比如奔驰的三叉星、宝马的蓝天白云、玛莎拉蒂的三叉戟，其背后都蕴藏着几十年乃至上百年的深厚历史。\n 但就在这些我们早就习以为常的logo背后，居然暗藏着不少鲜为人知的冷知识。\n吉利：666666\n（注：该回答来自知乎用户范履冰，已获作者授权，由猩猩宝宝加工整理）\n如今的吉利在自主品牌里可谓是各种高大上。不但坐拥北欧豪车品牌沃尔沃，还推出了领克这一高端自主品牌，简直羡煞一众自主品牌。\n但吉利也并非从一开始就如此“洋气”。说出来你可能不信，吉利最早的logo的设计灵感居然来源于“六六大顺”……";
//                order.out_trade_no = @"23416214123";
//                order.is_pay = YES;
//                order.is_accept = YES;
//                [dataArray addObject:order];
            }
            [self showOrHideDataView];
            [weakself.tableView reloadData];
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }
}

-(void)loadData
{
    WeakSelf(self)
    [self.listApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        
        if (kCode(request.responseJSONObject)) {
            if (weakself.listApi.page == 1) {
                [weakself.dataArray removeAllObjects];
            }
            NSArray *arr = [[request.responseJSONObject objectForKey:@"data"] objectForKey:@"list"];
            for (NSDictionary *dic in arr) {
                Order *order = [Order new];
                [order setValuesForKeysWithDictionary:dic];
                [weakself.dataArray addObject:order];
            }
        }
        [self showOrHideDataView];
        [weakself.tableView reloadData];
        [weakself endRefreshing];
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [weakself endRefreshing];
    }];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    CGFloat y = scrollView.contentOffset.y;
    if (y > 0 && y < 47) {
        if (y >= 46/2) {
            [scrollView setContentOffset:CGPointMake(0, 46) animated:YES];
        }else{
            [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    /*取消layer动画*/
    [CALayer cancelAnimation:^{
        CGRect layerFrame = self.redundantLayer.frame;
        layerFrame.origin.y = -layer_Y - y;
        self.redundantLayer.frame = layerFrame;
    }];
    
    if (y >= 1 && y <= 45) {
        [self.header_Y setValue:@(0 - y) forKey:@"layoutConstant"];
        [self.header setAlpha: y / 46.0];
        [self.header scrollProportion:y / 46.0];
    }else if (y >= 46){
        [self.header_Y setValue:@(-46) forKey:@"layoutConstant"];
        self.header.layerIsGarden = NO;
        [self.header setAlpha:1];
        [self.header scrollProportion:1];
    }else if (y <= 0){
        [self.header_Y setValue:@(0) forKey:@"layoutConstant"];
        [self.header setAlpha:0];
        self.header.layerIsGarden = YES;
        [self.header scrollProportion:0];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int type = [[self.listApi valueForKey:@"type"]intValue];
    Order *order = self.dataArray[indexPath.row];
    WeakSelf(self)

    if ((type == mianduimian_OrderType && !order.is_operationOrder) || (type == mianduimian_OrderType && order.refused_at)) {
        FaceToFaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FaceToFaceTableViewCell" forIndexPath:indexPath];
        [cell setOrder:order];
        cell.describe.spreadText = ^(id obj) {
            [CALayer cancelAnimation:^{
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            }];
        };
        
        cell.acceptBlock = ^(id obj) {
            OrderApi *api = [[OrderApi alloc]initRequestAccept:order.id];
            [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                if (kCode(request.responseJSONObject)) {
                    [Tool SendMessage_AcceptOrder:order.id hx_username:order.user_hx];
                    [weakself loadData];
                }
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
        };
        
        cell.refuseBlock = ^(id obj) {
            RefusedViewController *vc = [[RefusedViewController alloc]init];
            vc.order = order;
            [weakself pushViewController:vc animated:YES];
            
        };
        
        return cell;

    }else{
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderTableViewCell" forIndexPath:indexPath];
        
        if (type == mianduimian_OrderType) {
            if (order.is_operationOrder) {
                cell.time.hidden = NO;
                cell.time_H.constant = 17;
                cell.line_Top.constant = 8;
                NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:@"预约时间: " attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor blackColor]}];
                
                [attString appendAttributedString:[[NSAttributedString alloc] initWithString:order.serviced_at attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:k666666}]];
                cell.time.attributedText = attString;
                
            }else{
                cell.time.hidden = YES;
                cell.time_H.constant = 0;
                cell.line_Top.constant = -4;
            }
        }else{
            cell.time.hidden = YES;
            cell.time_H.constant = 0;
            cell.line_Top.constant = -4;
        }
        
        [cell setOrder:order type:type];
        
        cell.touchHeadPortrait = ^(id obj) {
            if (order.is_pay) {
                [weakself pushViewController:[PersonalDetailsViewController PersonalDetailsViewController:order UserID:order.user_id] animated:YES];
            }
        };
        
        cell.touchCheckDetails = ^(id obj) {
            [weakself pushViewController:[OrderDetailsViewController OrderDetailsViewController:order] animated:YES];
        };
        
        WeakSelf(cell)
        cell.touchCurriculumVitae = ^(id obj) {
            if (order.allow_check){
                //已同意去查看
                PersonalDetailsViewController *vc = [PersonalDetailsViewController PersonalDetailsViewController:order UserID:order.user_id];
                vc.isRecords = YES;
                [weakself pushViewController:vc animated:YES];
                
            }else{
                //未同意去申请
                OrderApi *api = [[OrderApi alloc] initRequestSendApplyForWithOrderID:order.id];
                api.needHUD = NO;
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                    if (kCode(request.responseJSONObject)) {
                        [MBProgressHUD showSuccess:@"已发送申请"];
                        order.allow_send_check = NO;
                        weakcell.applyForBtn.enabled = NO;
                        
                        [Tool SendMessage_ApplyForDiagnosisRecord:order.id hx_username:order.user_hx];
                    }else{
                        [MBProgressHUD showError:@"申请发送失败"];
                    }
                    
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    
                }];
            }
        };
        
        cell.describe.spreadText = ^(id obj) {
            [CALayer cancelAnimation:^{
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            }];
        };
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int type = [[self.listApi valueForKey:@"type"]intValue];
    Order *order = self.dataArray[indexPath.row];
    
    if ((type == mianduimian_OrderType && !order.is_operationOrder) || (type == mianduimian_OrderType && order.refused_at)) {
        if (order.is_timeout || order.refused_at) {
            return 118 + [order cellHeight];
        }else{
            return 155 + [order cellHeight];
        }
    }else{
        if (type == mianduimian_OrderType) {
            if (order.is_operationOrder) {
                return 210 + [order cellHeight];
            }
        }
    }
    return 178 + [order cellHeight];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(CGFloat)contentTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath andModel:(id)model
{
    return 75;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.header.height;
}

-(OrderHeaderView *)header
{
    if (!_header) {
        _header = [[OrderHeaderView alloc]init];
        WeakSelf(self)
        _header.actionBlock = ^(id obj) {
            [weakself showOrHideDataView];
            [weakself.tableView reloadData];
            [weakself endRefreshing];
        };
    }
    return _header;
}

-(NSArray<WKApi *> *)apis
{
    if (!_apis) {
        NSArray *types = @[@"1",@"2",@"3",@"4"];

        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < types.count; i++) {
            OrderListApi *api = [[OrderListApi alloc]initWithType:[types[i] intValue] completed:NO];
            [arr addObject:api];
        }
        _apis = arr;
    }
    return _apis;
}

-(NSArray<NSMutableArray *> *)datas
{
    if (!_datas) {
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < self.apis.count; i++) {
            NSMutableArray *data = [NSMutableArray array];
            [arr addObject:data];
        }
        _datas = arr;
    }
    return _datas;
}

-(WKApi *)listApi
{
    return [self.apis objectAtIndex:self.header.selectIndex];
}

-(NSMutableArray *)dataArray
{
    return [self.datas objectAtIndex:self.header.selectIndex];
}

//-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [self pushViewController:[[RefusedViewController alloc]init] animated:YES];
//    
//    
//    GaugeApi *api = [[GaugeApi alloc]init];
//    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//        if (kCode(request.responseJSONObject)) {
//            NSMutableArray *data = [NSMutableArray array];
//            NSArray *arr = [request.responseJSONObject objectForKey:@"data"];
//            for (NSDictionary *dic in arr) {
//                Scale *scale = [[Scale alloc]init];
//                [scale setValuesForKeysWithDictionary:dic];
//                [data addObject:scale];
//            }
//            
//            ClassificationViewController *vc = [[ClassificationViewController alloc]initWithDelegate:self registeredCell:^(UITableView *tableView) {
//        
//                [tableView registerNib:[UINib nibWithNibName:@"ClassificationCell" bundle:nil] forCellReuseIdentifier:@"ClassificationCell"];
//            }];
//            self.classificationVC = vc;
//        
//            vc.title = @"全部量表";
//            vc.categoryTableCellWidth = 90;
//            vc.categoryTableCellHieght = 50;
//        
//            [vc addDataArr:data];
//        
//            vc.categoryDefaultBackgroundColor = kF2F2F2;
//            vc.categorySelectBackgroundColor = [UIColor whiteColor];
//            [self pushViewController:vc animated:YES];
//        }
//    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//    
//    }];
//}
//
//-(UITableViewCell *)contentTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath andModel:(id)model
//{
//    ClassificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ClassificationCell" forIndexPath:indexPath];
//    
//    Scale *subClass = model;
//    WeakSelf(self)
//    cell.selectBtn.selected = subClass.selected;
//    cell.title.text = subClass.title;
//    cell.price.text = [NSString stringWithFormat:@"%@%0.2f",RENMINGBI,subClass.price];
//    [cell.image sd_setImageWithURL:[NSURL URLWithString:subClass.image]];
//    
//    cell.selectAction = ^(UIButton *obj) {
//        subClass.selected = obj.selected;
//        if (obj.selected) {
//            [weakself.classificationVC selcetObject:model];
//        }else {
//            [weakself.classificationVC cancelSelcetObject:model];
//        }
//    };
//    
//    return cell;
//}
//-(UIView *)contentTableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section andModel:(id<CategoryModel>)model
//{
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 90, 30)];
//    label.backgroundColor = [UIColor whiteColor];
//    label.font = [UIFont systemFontOfSize:14];
//    label.text = model.categoryTitle;
//    return label;
//}
//-(CGFloat )contentTableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section andModel:(id<CategoryModel>)model
//{
//    return 30;
//}


@end
